const { Service } = require('egg');
const userMock = require('./mock/user/usermock');

module.exports = class UserService extends Service {

  constructor(ctx) {
    super(ctx);
    this.root = 'https://api.egg.erchoc.com/v1';
  }

  // 封装请求URL
  async request(url, opts) {
    url = `${this.root}${url}`;
    opts = Object.assign({
      timeout: [ '30s', '30s' ],
      dataType: 'json',
    }, opts);
    return this.ctx.curl(url, opts);
  }

  // 创建资源
  async create(params) {
    console.log(params);
    // TODO PRC调用后端服务
    const result = userMock.userInfo;

    this.checkSuccess(result);
    return result.data;
  }

  // 删除资源(soft delete)
  async delete(params) {
    console.log(params);
    // TODO RPC调用后端服务
    const result = {
      error: 0,
      msg: "删除资源成功",
    };
    this.checkSuccess(result);
    return result.data;
  }

  // 更新资源信息
  async update(params) {
    console.log(params);
    // TODO PRC调用后端服务
    const result = userMock.userInfo;

    this.checkSuccess(result);
    return result.data;
  }

  // 查找资源信息
  async show(params) {
    console.log(params);
    // TODO PRC调用后端服务
    const result = userMock.userInfo;

    this.checkSuccess(result);
    return result.data;
  }

  // 显示资源列表
  async index(params) {
    console.log(params);
    // TODO PRC调用后端服务
    const result = userMock.usersList;

    this.checkSuccess(result);
    return result.data;
  }

  // 检查数据获取是否正常
  checkSuccess( result ) {
    if (result.error === 1) {
      // 服务器内部出错
      this.ctx.throw(500, 'remote response error', { data: result.data });
    }
  }

};
